<template>
  <Layout>
    <div class="profile-section">
      <el-card class="profile-card">
        <template #header>
          <div class="card-header">
            <h3>个人信息</h3>
            <el-button type="primary" @click="editMode = true" v-if="!editMode">
              <el-icon><Edit /></el-icon>编辑
            </el-button>
          </div>
        </template>
        
        <!-- 查看模式 -->
        <div v-if="!editMode" class="profile-info">
          <div class="avatar-section">
            <el-avatar :size="100" :src="userInfo.avatar || defaultAvatar"></el-avatar>
          </div>
          
          <div class="info-section">
            <div class="info-item">
              <span class="info-label">用户名</span>
              <span class="info-value">{{ userInfo.username }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">真实姓名</span>
              <span class="info-value">{{ userInfo.realName || '未设置' }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">手机号码</span>
              <span class="info-value">{{ userInfo.phone || '未设置' }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">电子邮箱</span>
              <span class="info-value">{{ userInfo.email || '未设置' }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">注册时间</span>
              <span class="info-value">{{ formatDateTime(userInfo.createTime) }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">最后登录</span>
              <span class="info-value">{{ formatDateTime(userInfo.lastLoginTime) }}</span>
            </div>
          </div>
        </div>
        
        <!-- 编辑模式 -->
        <div v-else class="profile-edit">
          <el-form 
            :model="userForm" 
            :rules="formRules" 
            ref="userFormRef" 
            label-width="100px"
            class="profile-form"
          >
            <div class="avatar-upload">
              <el-avatar :size="100" :src="userForm.avatar || defaultAvatar"></el-avatar>
              <el-button size="small" type="primary" class="upload-btn" @click="handleUploadClick">
                <el-icon><Upload /></el-icon>更换头像
              </el-button>
              <el-upload
                class="hidden-upload"
                action="#"
                :http-request="handleAvatarUpload"
                :show-file-list="false"
                accept="image/*"
              >
                <el-button class="hidden-btn" ref="uploadBtn"></el-button>
              </el-upload>
            </div>
            
            <el-form-item label="用户名" prop="username">
              <el-input v-model="userForm.username" disabled></el-input>
            </el-form-item>
            
            <el-form-item label="真实姓名" prop="realName">
              <el-input v-model="userForm.realName" placeholder="请输入真实姓名"></el-input>
            </el-form-item>
            
            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="userForm.phone" placeholder="请输入手机号码" disabled></el-input>
            </el-form-item>
            
            <el-form-item label="电子邮箱" prop="email">
              <el-input v-model="userForm.email" placeholder="请输入电子邮箱"></el-input>
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="saveUserInfo">保存</el-button>
              <el-button @click="cancelEdit">取消</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
      
      <el-card class="security-card">
        <template #header>
          <div class="card-header">
            <h3>安全设置</h3>
          </div>
        </template>
        
        <div class="security-section">
          <div class="security-item">
            <div class="security-info">
              <div class="security-title">修改登录密码</div>
              <div class="security-desc">定期修改密码可以保护账户安全</div>
            </div>
            <el-button type="primary" plain @click="showPasswordDialog = true">修改</el-button>
          </div>
          
          <div class="security-item">
            <div class="security-info">
              <div class="security-title">绑定手机号码</div>
              <div class="security-desc">绑定手机后可通过手机号登录，找回密码等</div>
            </div>
            <el-button type="primary" plain disabled>已绑定</el-button>
          </div>
          
          <div class="security-item">
            <div class="security-info">
              <div class="security-title">绑定邮箱</div>
              <div class="security-desc">绑定邮箱后可通过邮箱接收重要通知</div>
            </div>
            <el-button 
              type="primary" 
              plain 
              @click="userInfo.email ? handleUnbindEmail() : showEmailBindDialog = true"
            >
              {{ userInfo.email ? '解绑' : '绑定' }}
            </el-button>
          </div>
          
          <div class="security-item">
            <div class="security-info">
              <div class="security-title">账户安全评分</div>
              <div class="security-desc">提高账户安全评分可以加强账户安全</div>
            </div>
            <div class="security-score">
              <el-progress 
                :percentage="calculateSecurityScore()" 
                :color="getProgressColor()"
                :format="formatPercentage"
                :stroke-width="14"
              ></el-progress>
            </div>
          </div>
        </div>
      </el-card>
      
      <el-card class="account-card">
        <template #header>
          <div class="card-header">
            <h3>账户信息</h3>
          </div>
        </template>
        
        <div class="account-info">
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="8">
              <div class="account-item">
                <div class="account-label">账户余额</div>
                <div class="account-value">{{ formatCurrency(userInfo.balance) }}</div>
              </div>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8">
              <div class="account-item">
                <div class="account-label">冻结金额</div>
                <div class="account-value">{{ formatCurrency(userInfo.frozenAmount) }}</div>
              </div>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8">
              <div class="account-item">
                <div class="account-label">可用金额</div>
                <div class="account-value">{{ formatCurrency(calculateAvailableAmount()) }}</div>
              </div>
            </el-col>
          </el-row>
          
          <div class="action-buttons">
            <el-button type="primary">充值</el-button>
            <el-button type="success">提现</el-button>
            <el-button type="info">交易记录</el-button>
          </div>
        </div>
      </el-card>
    </div>
    
    <!-- 修改密码对话框 -->
    <el-dialog
      v-model="showPasswordDialog"
      title="修改密码"
      width="500px"
      destroy-on-close
    >
      <el-form 
        :model="passwordForm" 
        :rules="passwordRules" 
        ref="passwordFormRef" 
        label-width="100px"
      >
        <el-form-item label="原密码" prop="oldPassword">
          <el-input 
            v-model="passwordForm.oldPassword" 
            placeholder="请输入原密码" 
            show-password
          ></el-input>
        </el-form-item>
        
        <el-form-item label="新密码" prop="newPassword">
          <el-input 
            v-model="passwordForm.newPassword" 
            placeholder="请输入新密码" 
            show-password
          ></el-input>
        </el-form-item>
        
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input 
            v-model="passwordForm.confirmPassword" 
            placeholder="请再次输入新密码" 
            show-password
          ></el-input>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showPasswordDialog = false">取消</el-button>
          <el-button type="primary" @click="changePasswordAction" :loading="passwordLoading">确认</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 绑定邮箱对话框 -->
    <el-dialog
      v-model="showEmailBindDialog"
      title="绑定邮箱"
      width="500px"
      destroy-on-close
    >
      <el-form 
        :model="emailBindForm" 
        :rules="emailRules" 
        ref="emailBindFormRef" 
        label-width="100px"
      >
        <el-form-item label="邮箱地址" prop="email">
          <el-input 
            v-model="emailBindForm.email" 
            placeholder="请输入邮箱地址"
          ></el-input>
        </el-form-item>
        
        <el-form-item label="验证码" prop="verificationCode">
          <div class="code-input-group">
            <el-input 
              v-model="emailBindForm.verificationCode" 
              placeholder="请输入6位数字验证码"
              maxlength="6"
              style="flex: 1; margin-right: 10px;"
            ></el-input>
            <el-button 
              @click="sendEmailCode" 
              :loading="emailCodeSending"
              :disabled="emailCodeCountdown > 0"
            >
              {{ emailCodeCountdown > 0 ? `${emailCodeCountdown}s` : '发送验证码' }}
            </el-button>
          </div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showEmailBindDialog = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="handleBindEmail" 
            :loading="emailBindLoading"
          >
            确认绑定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </Layout>
</template>

<script setup name="UserProfileView">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import Cookies from 'js-cookie';
import { Edit, Upload } from '@element-plus/icons-vue';
import { useUserStore } from '@/store/user';
import { getUserInfo, updateUserInfo, changePassword, uploadAvatar, updateAvatar } from '@/api/user';
import { getSecuritySettings, getSecurityScore, bindEmail, unbindEmail, sendEmailVerificationCode } from '@/api/security';
import Layout from '@/components/layout/Layout.vue';

// 状态管理
const userStore = useUserStore();

// 用户信息和表单
const userInfo = reactive(userStore.userInfo || {});
const userFormRef = ref(null);
const userForm = reactive({
  username: '',
  realName: '',
  phone: '',
  email: '',
  avatar: ''
});

// 默认头像
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png';

// 编辑模式
const editMode = ref(false);

// 安全设置相关
const securitySettings = reactive({});
const securityScore = reactive({});
const showEmailBindDialog = ref(false);
const emailBindForm = reactive({
  email: '',
  verificationCode: ''
});
const emailBindFormRef = ref(null);
const emailCodeSending = ref(false);
const emailCodeCountdown = ref(0);
const emailBindLoading = ref(false);

// 邮箱验证规则
const emailRules = {
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/, message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  verificationCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { pattern: /^\d{6}$/, message: '验证码为6位数字', trigger: 'blur' }
  ]
};

// 密码相关
const showPasswordDialog = ref(false);
const passwordFormRef = ref(null);
const passwordLoading = ref(false);
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
});

// 表单验证规则
const formRules = {
  realName: [
    { max: 50, message: '真实姓名不能超过50个字符', trigger: 'blur' }
  ],
  email: [
    { pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/, message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
};

// 密码验证规则
const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入新密码'));
  } else {
    if (passwordForm.confirmPassword !== '') {
      if (passwordFormRef.value) {
        passwordFormRef.value.validateField('confirmPassword');
      }
    }
    callback();
  }
};

const validateConfirmPass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入新密码'));
  } else if (value !== passwordForm.newPassword) {
    callback(new Error('两次输入的密码不一致'));
  } else {
    callback();
  }
};

const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在6到20个字符之间', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在6到20个字符之间', trigger: 'blur' },
    { validator: validatePass, trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { validator: validateConfirmPass, trigger: 'blur' }
  ]
};

// 日期时间格式化
const formatDateTime = (dateTime) => {
  if (!dateTime) return '暂无数据';
  
  const date = new Date(dateTime);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}`;
};

// 格式化货币
const formatCurrency = (value) => {
  if (value === undefined || value === null) return '¥ 0.00';
  return `¥ ${parseFloat(value).toFixed(2)}`;
};

// 计算可用金额
const calculateAvailableAmount = () => {
  const balance = parseFloat(userInfo.balance || 0);
  const frozen = parseFloat(userInfo.frozenAmount || 0);
  return Math.max(0, balance - frozen);
};

// 计算安全评分
const calculateSecurityScore = () => {
  return securityScore.totalScore || 60;
};

// 获取进度条颜色
const getProgressColor = () => {
  const score = calculateSecurityScore();
  if (score < 70) return '#F56C6C'; // 红色
  if (score < 85) return '#E6A23C'; // 橙色
  return '#67C23A'; // 绿色
};

// 格式化百分比
const formatPercentage = () => {
  const score = calculateSecurityScore();
  const level = securityScore.securityLevel || '低';
  return `${score}分 - ${level}`;
};

// 初始化表单数据
const initFormData = () => {
  userForm.username = userInfo.username || '';
  userForm.realName = userInfo.realName || '';
  userForm.phone = userInfo.phone || '';
  userForm.email = userInfo.email || '';
  userForm.avatar = userInfo.avatar || '';
};

// 发送邮箱验证码
const sendEmailCode = async () => {
  if (!emailBindForm.email) {
    ElMessage.error('请先输入邮箱地址');
    return;
  }
  
  try {
    emailCodeSending.value = true;
    
    await sendEmailVerificationCode(emailBindForm.email, 'bind');
    
    ElMessage.success('验证码已发送到邮箱');
    
    // 开始倒计时
    emailCodeCountdown.value = 60;
    const timer = setInterval(() => {
      emailCodeCountdown.value--;
      if (emailCodeCountdown.value <= 0) {
        clearInterval(timer);
      }
    }, 1000);
  } catch (error) {
    console.error('发送验证码失败:', error);
    ElMessage.error('发送验证码失败，请重试');
  } finally {
    emailCodeSending.value = false;
  }
};

// 绑定邮箱
const handleBindEmail = async () => {
  if (!emailBindFormRef.value) return;
  
  await emailBindFormRef.value.validate(async (valid) => {
    if (valid) {
      emailBindLoading.value = true;
      
      try {
        const response = await bindEmail(emailBindForm.email, emailBindForm.verificationCode);
        
        if (response.code === 0) {
          ElMessage.success('邮箱绑定成功');
          showEmailBindDialog.value = false;
          
          // 重置表单
          emailBindForm.email = '';
          emailBindForm.verificationCode = '';
          
          // 重新获取用户信息和安全设置
          await fetchUserInfo();
          await fetchSecuritySettings();
          await fetchSecurityScore();
        }
      } catch (error) {
        console.error('绑定邮箱失败:', error);
        ElMessage.error('绑定邮箱失败，请检查验证码是否正确');
      } finally {
        emailBindLoading.value = false;
      }
    }
  });
};

// 解绑邮箱
const handleUnbindEmail = () => {
  ElMessageBox.confirm('解绑邮箱后将失去邮箱安全验证功能，是否继续？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      // 这里简化处理，实际应该先发送验证码再解绑
      const response = await unbindEmail('123456');
      
      if (response.code === 0) {
        ElMessage.success('邮箱解绑成功');
        
        // 重新获取用户信息和安全设置
        await fetchUserInfo();
        await fetchSecuritySettings();
        await fetchSecurityScore();
      }
    } catch (error) {
      console.error('解绑邮箱失败:', error);
      ElMessage.error('解绑邮箱失败，请重试');
    }
  });
};

// 取消编辑
const cancelEdit = () => {
  editMode.value = false;
  initFormData(); // 重置表单数据
};

// 保存用户信息
const saveUserInfo = async () => {
  if (!userFormRef.value) return;
  
  await userFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 调用更新接口
        const response = await updateUserInfo(userForm);
        
        if (response.code === 0) {
          // 更新本地存储的用户信息
          Object.assign(userInfo, response.data);
          userStore.setUserInfo(response.data);
          
          ElMessage.success('个人信息更新成功');
          editMode.value = false;
        }
      } catch (error) {
        console.error('更新用户信息失败:', error);
        ElMessage.error('更新用户信息失败，请重试');
      }
    }
  });
};

// 处理头像上传
const uploadBtn = ref(null);
const handleUploadClick = () => {
  if (uploadBtn.value) {
    uploadBtn.value.$el.click();
  }
};

const handleAvatarUpload = async (options) => {
  const file = options.file;
  
  // 验证文件大小
  if (file.size > 2 * 1024 * 1024) {
    ElMessage.error('头像文件大小不能超过2MB');
    return;
  }
  
  // 验证文件类型
  const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'];
  if (!allowedTypes.includes(file.type)) {
    ElMessage.error('只支持jpg、png、gif、webp格式的图片');
    return;
  }
  
  try {
    ElMessage.info('头像上传中...');
    
    // 上传头像到服务器
    const uploadResponse = await uploadAvatar(file);
    
    if (uploadResponse.code === 0) {
      const avatarUrl = uploadResponse.data.url;
      
      // 更新头像
      const updateResponse = await updateAvatar(avatarUrl);
      
      if (updateResponse.code === 0) {
        // 更新本地表单数据
        userForm.avatar = avatarUrl;
        
        // 更新用户信息
        Object.assign(userInfo, updateResponse.data);
        userStore.setUserInfo(updateResponse.data);
        
        ElMessage.success('头像上传成功');
      }
    }
  } catch (error) {
    console.error('头像上传失败:', error);
    ElMessage.error('头像上传失败，请重试');
  }
};

// 修改密码
const changePasswordAction = async () => {
  if (!passwordFormRef.value) return;
  
  await passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      passwordLoading.value = true;
      
      try {
        // 调用修改密码接口
        const response = await changePassword(
          passwordForm.oldPassword,
          passwordForm.newPassword,
          passwordForm.confirmPassword
        );
        
        if (response.code === 0) {
          ElMessage.success('密码修改成功，请重新登录');
          showPasswordDialog.value = false;
          
          // 清除cookie和状态，跳转到登录页
          Cookies.remove('virtual_bank_token');
          Cookies.remove('token');
          userStore.resetState();
          
          // 延迟跳转
          setTimeout(() => {
            window.location.href = '/login';
          }, 1500);
        }
      } catch (error) {
        console.error('修改密码失败:', error);
        ElMessage.error('修改密码失败，请重试');
      } finally {
        passwordLoading.value = false;
      }
    }
  });
};

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const response = await getUserInfo();
    if (response.code === 0) {
      Object.assign(userInfo, response.data);
      userStore.setUserInfo(response.data);
      initFormData();
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);
    ElMessage.error('获取用户信息失败，请刷新重试');
  }
};

// 获取安全设置
const fetchSecuritySettings = async () => {
  try {
    const response = await getSecuritySettings();
    if (response.code === 0) {
      Object.assign(securitySettings, response.data);
    }
  } catch (error) {
    console.error('获取安全设置失败:', error);
  }
};

// 获取安全评分
const fetchSecurityScore = async () => {
  try {
    const response = await getSecurityScore();
    if (response.code === 0) {
      Object.assign(securityScore, response.data);
    }
  } catch (error) {
    console.error('获取安全评分失败:', error);
  }
};

// 页面加载时获取用户信息
onMounted(async () => {
  // 获取用户信息
  await fetchUserInfo();
  
  // 获取安全设置
  await fetchSecuritySettings();
  
  // 获取安全评分
  await fetchSecurityScore();
  
  // 初始化表单数据
  initFormData();
});
</script>

<style scoped>
.profile-section {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.profile-card, .security-card, .account-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.profile-info {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.avatar-section {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.info-section {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 15px;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.info-label {
  color: #909399;
  font-size: 14px;
}

.info-value {
  font-size: 16px;
  color: #303133;
}

.profile-edit {
  padding: 10px;
}

.profile-form {
  max-width: 600px;
  margin: 0 auto;
}

.avatar-upload {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 20px;
  gap: 10px;
}

.upload-btn {
  margin-top: 10px;
}

.hidden-upload {
  display: none;
}

.security-section {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.security-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #ebeef5;
}

.security-item:last-child {
  border-bottom: none;
}

.security-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 5px;
}

.security-desc {
  font-size: 14px;
  color: #909399;
}

.security-score {
  width: 200px;
}

.account-info {
  padding: 10px 0;
}

.account-item {
  background: linear-gradient(90deg, #f5f7fa, #eef3f9);
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 15px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
}

.account-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.account-value {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.action-buttons {
  margin-top: 20px;
  display: flex;
  gap: 10px;
  justify-content: center;
}

@media (max-width: 768px) {
  .info-section {
    grid-template-columns: 1fr;
  }
  
  .security-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .security-score {
    width: 100%;
  }
  
  .action-buttons {
    flex-direction: column;
    width: 100%;
  }
  
  .action-buttons .el-button {
    width: 100%;
    margin-left: 0 !important;
    margin-right: 0 !important;
    margin-bottom: 10px;
  }
  
  .code-input-group {
    flex-direction: column;
    gap: 10px;
  }
  
  .code-input-group .el-input {
    margin-right: 0 !important;
  }
}

.code-input-group {
  display: flex;
  align-items: center;
}
</style>
